package org.droidcon.apps.template.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.droidcon.apps.template.provider.ScheduleContract.Sessions;
import org.droidcon.apps.template.provider.ScheduleContract.Speakers;
import org.droidcon.apps.template.provider.ScheduleContract.Tracks;
import org.droidcon.apps.template.provider.ScheduleDatabase.SessionsTracks;
import org.droidcon.apps.template.util.UIUtils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class HTMLExporter {

	public static interface HtmlHandler {

		void beforeFirstEntry(Writer f);
		void afterLastEntry(Writer f);
		void afterWriteEntry(String title, String droidconId, String blog,
				String drupalNid);

		void writeEntry(StringWriter f, Cursor cursorSession, Cursor cursorSpeaker, Cursor trackCursor, Context context);

	}

	public static void exportSessions(Context context, boolean appDir, String filename, HtmlHandler htmlHandler) {
		Cursor cursor = context.getContentResolver().query(
				Sessions.CONTENT_URI, null, Sessions.BLOCK_START + " >= " + UIUtils.START_DAY_2 +" AND " + Sessions.BLOCK_START + " < " + UIUtils.START_DAY_3, null, Sessions.BLOCK_START + ", " + Sessions.ROOM_ID);
		if (cursor.getCount() == 0){
			cursor.close();
			return;
		}
		cursor.moveToFirst();

		File path = null; 
		
		if (appDir){
			path = context.getDir("export", Context.MODE_WORLD_WRITEABLE);			
		} else {
			path = Environment
				.getExternalStorageDirectory();
		}
		
		File file = new File(path, filename);
		path.mkdirs();
		Log.v("export", "export to file:" + file.getAbsolutePath());
		
		try {
			file.createNewFile();
			
			FileWriter fileWriter = new FileWriter(file);
			
			htmlHandler.beforeFirstEntry(fileWriter);
			
			do {
				StringWriter f = new StringWriter();
				String sessionId = cursor.getString(cursor
						.getColumnIndex(Sessions.SESSION_ID));
				
				final Uri speakersUri = Sessions.buildSpeakersDirUri(sessionId);

				Cursor cursor2 = context.getContentResolver().query(
						speakersUri, null, null, null, null);				
				
				cursor2.moveToFirst();
				
				final Uri trackUri = Sessions.buildTracksDirUri(sessionId);
				Cursor trackCursor = context.getContentResolver().query(trackUri, null, null, null, null);
				trackCursor.moveToFirst();
				
				htmlHandler.writeEntry(f, cursor, cursor2, trackCursor, context);
				
//				f.append("</ul>\n");
				
				cursor2.close();
				trackCursor.close();
				
				htmlHandler.afterWriteEntry(cursor.getString(cursor
						.getColumnIndex(Sessions.SESSION_TITLE)), sessionId, f.toString(), cursor.getString(cursor.getColumnIndex(Sessions.SESSION_FEEDBACK_URL)));
				fileWriter.append(f.toString());
				
			} while (cursor.moveToNext());
			cursor.close();

			htmlHandler.afterLastEntry(fileWriter);
			fileWriter.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	

	}

	public static void exportSpeakers(Context context, boolean appDir) {
		Cursor cursor = context.getContentResolver().query(
				Speakers.CONTENT_URI, null, null, null, Speakers.SPEAKER_NAME);
		if (cursor.getCount() == 0){
			cursor.close();
			return;
		}

		cursor.moveToFirst();

		File path = null; 
		
		if (appDir){
			path = context.getDir("export", Context.MODE_WORLD_WRITEABLE);			
		} else {
			path = Environment
				.getExternalStoragePublicDirectory("downloads");
		}
		
		File file = new File(path, "speakers.html");
		path.mkdirs();
		
		try {
			file.createNewFile();
			
			FileWriter f = new FileWriter(file);
			
			f.append("<table>");
			do {
				String speakerId = cursor.getString(cursor
						.getColumnIndex(Speakers.SPEAKER_ID));
				
				final Uri sessionsUri = Speakers.buildSessionsDirUri(speakerId);

				Cursor cursor2 = context.getContentResolver().query(
						sessionsUri, null, null, null, Sessions.BLOCK_START + ", " + Sessions.ROOM_ID);
				
				cursor2.moveToFirst();
				f.append("<tr><td>");
				f.append("<img width=\"100\" src=\"http://de.droidcon.com/images/speakers_2011/");
				f.append(cursor.getString(cursor.getColumnIndex(Speakers.SPEAKER_URL)));
				f.append("\"/>");
				f.append("</td><td><b>");
				f.append(cursor.getString(cursor
						.getColumnIndex(Speakers.SPEAKER_NAME)));
				f.append("</b><br/>");
				f.append(cursor.getString(cursor
						.getColumnIndex(Speakers.SPEAKER_COMPANY)));
				f.append("<br/>");
				f.append(cursor.getString(cursor
						.getColumnIndex(Speakers.SPEAKER_ABSTRACT)));				
				f.append("<br/>");
				do {
					f.append("<br/><em>");
					f.append(cursor2.getString(cursor2
							.getColumnIndex(Sessions.SESSION_TITLE)));
					f.append("</em>");
					final long blockStart = cursor2.getLong(cursor2
							.getColumnIndex(Sessions.BLOCK_START));
					final long blockEnd = cursor2.getLong(cursor2
							.getColumnIndex(Sessions.BLOCK_END));
					final String roomName = cursor2.getString(cursor2
							.getColumnIndex(Sessions.ROOM_NAME));

					f.append(" (" + UIUtils.formatSessionSubtitle(blockStart, blockEnd, roomName, context) + ")");
					
				} while (cursor2.moveToNext());
				f.append("</td></tr>\n");
				
				cursor2.close();
			} while (cursor.moveToNext());
			cursor.close();
			f.append("</table>");
			f.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	

	}

}
